package com.das.mechanic_base.utils;

import android.os.Parcelable;

import com.das.mechanic_base.bean.process.ProcessName;
import com.tencent.mmkv.MMKV;


/**
 * Created by chensi on 2018/4/11.
 */

public class SpHelper {

    private static MMKV kv = MMKV.mmkvWithID("IT_InterProcessKV", MMKV.MULTI_PROCESS_MODE);

    /**
     * 清除全部key
     */
    public void clearAll() {
        kv.clearAll();
    }

    /**
     * 保存数据
     *
     * @param key
     * @param data
     */
    public static void saveData(String key, Object data) {
        String type = data.getClass().getSimpleName();

        if ("Integer".equals(type)) {
            kv.encode(key, (Integer) data);
        } else if ("Boolean".equals(type)) {
            kv.encode(key, (Boolean) data);
        } else if ("String".equals(type)) {
            kv.encode(key, (String) data);
        } else if ("Float".equals(type)) {
            kv.encode(key, (Float) data);
        } else if ("Long".equals(type)) {
            kv.encode(key, (Long) data);
        }
    }

    /**
     * 得到数据
     *
     * @param key
     * @param defValue
     * @return
     */
    public static Object getData(String key, Object defValue) {
        String type = defValue.getClass().getSimpleName();
        if ("Integer".equals(type)) {
            return kv.decodeInt(key, (Integer) defValue);
        } else if ("Boolean".equals(type)) {
            return kv.decodeBool(key, (Boolean) defValue);
        } else if ("String".equals(type)) {
            return kv.decodeString(key, (String) defValue);
        } else if ("Float".equals(type)) {
            return kv.decodeFloat(key, (Float) defValue);
        } else if ("Long".equals(type)) {

            Object tmp = null;
            try {
                tmp = kv.decodeLong(key, (Long) defValue);
            }catch (Exception e){
                e.printStackTrace();
            }
            if (tmp == null){
                Integer tk = Integer.parseInt(String.valueOf(defValue));
                tmp = kv.decodeInt(key, tk);
            }
            if (tmp instanceof Long){
                return tmp;
            }
            if (tmp instanceof Integer){
                long tl = Long.parseLong(tmp+"");
                return tl;
            }
            return kv.decodeLong(key, (Long) defValue);
        }

        return null;
    }

    public static void saveData(String key, Parcelable cls) {
        kv.encode(key,  cls);
    }

    public static ProcessName getProcessName(String key){
        return kv.decodeParcelable(key, ProcessName.class);
    }
}
